<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 采购入库管理
 */
class PurchaseInbound extends Backend
{
    /**
     * PurchaseInbound模型对象
     * @var \app\admin\model\scanwork\PurchaseInbound
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\PurchaseInbound;
        
        // 获取供应商列表
        $supplierList = \app\admin\model\scanwork\Supplier::where('status', 1)->column('name', 'id');
        $this->view->assign("supplierList", $supplierList);
        
        // 获取仓库列表
        $warehouseList = \app\admin\model\scanwork\Warehouse::where('status', 1)->column('warehouse_name', 'id');
        $this->view->assign("warehouseList", $warehouseList);
    }

    /**
     * 查看
     */
    public function index()
    {
        // 禁用关联查询
        $this->relationSearch = false;
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            // 禁用selectpage调用
            // if ($this->request->request('keyField')) {
            //     return $this->selectpage();
            // }
            // 手动构建查询条件，避免buildparams的关联查询
            $where = [];
            $sort = $this->request->get('sort', 'id');
            $order = $this->request->get('order', 'desc');
            $offset = $this->request->get('offset', 0);
            $limit = $this->request->get('limit', 10);

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            // 手动获取关联数据
            foreach ($list->items() as $row) {
                $row->supplier = \app\admin\model\scanwork\Supplier::where('id', $row->supplier_id)->field('id, name')->find();
                $row->warehouse = \app\admin\model\scanwork\Warehouse::where('id', $row->warehouse_id)->field('id, warehouse_name')->find();
                // 获取操作员信息
                if ($row->inbound_user_id) {
                    $row->inbound_user = \app\admin\model\Admin::where('id', $row->inbound_user_id)->field('id, username')->find();
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 生成入库单号
                $params['inbound_no'] = 'IN' . date('YmdHis') . rand(1000, 9999);
                
                // 设置入库日期
                if (empty($params['inbound_date'])) {
                    $params['inbound_date'] = time();
                } else {
                    $params['inbound_date'] = strtotime($params['inbound_date']);
                }
                
                // 设置操作员ID（如果状态是已入库）
                if (isset($params['status']) && $params['status'] == 2) {
                    $params['inbound_user_id'] = $this->auth->id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    // 是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 处理入库日期
                if (!empty($params['inbound_date'])) {
                    $params['inbound_date'] = strtotime($params['inbound_date']);
                }
                
                // 设置操作员ID（如果状态是已入库且之前不是已入库状态）
                if (isset($params['status']) && $params['status'] == 2 && $row->status != 2) {
                    $params['inbound_user_id'] = $this->auth->id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    // 是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    $count += $item->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 从采购申请生成入库单
     */
    public function generateFromRequest()
    {
        if ($this->request->isPost()) {
            $requestIds = $this->request->post('request_ids');
            if (empty($requestIds)) {
                $result = [
                    'code' => 0,
                    'msg' => '请选择要生成入库单的采购申请',
                    'data' => []
                ];
                return json($result);
            }

            Db::startTrans();
            try {
                // 获取采购申请数据
                $requests = \app\admin\model\scanwork\PurchaseRequest::where('id', 'in', $requestIds)
                    ->where('status', 2) // 已审核的申请
                    ->select();

                if (empty($requests)) {
                    throw new Exception('没有找到已审核的采购申请');
                }

                // 按供应商分组
                $supplierGroups = [];
                foreach ($requests as $request) {
                    $supplierId = $request->supplier_id;
                    if (!isset($supplierGroups[$supplierId])) {
                        $supplierGroups[$supplierId] = [];
                    }
                    $supplierGroups[$supplierId][] = $request;
                }

                $inboundIds = [];
                foreach ($supplierGroups as $supplierId => $supplierRequests) {
                    // 创建入库单
                    $inbound = new \app\admin\model\scanwork\PurchaseInbound();
                    $inbound->inbound_no = 'IN' . date('YmdHis') . rand(1000, 9999);
                    $inbound->supplier_id = $supplierId;
                    $inbound->inbound_date = time();
                    $inbound->status = 1; // 待入库
                    $inbound->warehouse_id = 1; // 默认仓库
                    $inbound->total_amount = 0; // 初始总金额为0，后续从明细中计算
                    $inbound->save();

                    $inboundIds[] = $inbound->id;

                    // 创建入库明细
                    foreach ($supplierRequests as $request) {
                        $item = new \app\admin\model\scanwork\PurchaseInboundItem();
                        $item->inbound_id = $inbound->id;
                        $item->material_id = $request->material_id;
                        $item->request_quantity = $request->request_quantity;
                        $item->actual_quantity = $request->request_quantity; // 默认实际数量等于申请数量
                        $item->unit_price = $request->actual_price ?: 0; // 从采购申请中获取价格
                        $item->total_amount = $item->actual_quantity * $item->unit_price; // 计算总金额
                        $item->quality_status = 1; // 待检
                        $item->save();

                        // 更新采购申请状态
                        $request->status = 3; // 已采购
                        $request->save();
                    }
                    
                    // 更新入库单总金额
                    $this->updateInboundTotalAmount($inbound->id);
                }

                Db::commit();
                
                $result = [
                    'code' => 1,
                    'msg' => '入库单生成成功',
                    'data' => ['inbound_ids' => $inboundIds]
                ];
                return json($result);
                
            } catch (Exception $e) {
                Db::rollback();
                $result = [
                    'code' => 0,
                    'msg' => '生成失败：' . $e->getMessage(),
                    'data' => []
                ];
                return json($result);
            }
        }

        // 获取已审核的采购申请
        $requests = \app\admin\model\scanwork\PurchaseRequest::where('status', 2)->select();
        
        // 手动获取关联数据
        foreach ($requests as $request) {
            $request->material = \app\admin\model\scanwork\Material::find($request->material_id);
            $request->supplier = \app\admin\model\scanwork\Supplier::find($request->supplier_id);
        }

        $this->view->assign('requests', $requests);
        return $this->view->fetch();
    }

    /**
     * 确认入库
     */
    public function confirmInbound($ids = null)
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        
        $ids = $ids ? $ids : $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        Db::startTrans();
        try {
            $inbounds = \app\admin\model\scanwork\PurchaseInbound::where('id', 'in', $ids)
                ->where('status', 1) // 只处理待入库状态
                ->with(['items'])
                ->select();

            foreach ($inbounds as $inbound) {
                foreach ($inbound->items as $item) {
                    // 更新物料库存
                    $material = \app\admin\model\scanwork\Material::find($item->material_id);
                    if ($material) {
                        $beforeStock = $material->stock;
                        $afterStock = $beforeStock + $item->actual_quantity;
                        
                        $material->stock = $afterStock;
                        $material->save();

                        // 记录库存变动
                        $record = new \app\admin\model\scanwork\InventoryRecord();
                        $record->material_id = $item->material_id;
                        $record->inbound_id = $inbound->id;
                        $record->type = 1; // 入库
                        $record->quantity = $item->actual_quantity;
                        $record->before_stock = $beforeStock;
                        $record->after_stock = $afterStock;
                        $record->unit_price = $item->unit_price;
                        $record->batch_no = $item->batch_no;
                        $record->operator_id = $this->auth->id;
                        $record->operate_time = time();
                        $record->save();
                    }
                }

                // 更新入库单状态
                $inbound->status = 2; // 已入库
                $inbound->inbound_user_id = $this->auth->id;
                $inbound->save();
            }

            Db::commit();
            $this->success('入库确认成功');
            
        } catch (Exception $e) {
            Db::rollback();
            $this->error('确认失败：' . $e->getMessage());
        }
    }

    /**
     * 更新入库单总金额
     */
    private function updateInboundTotalAmount($inboundId)
    {
        // 计算入库明细的总金额
        $totalAmount = \app\admin\model\scanwork\PurchaseInboundItem::where('inbound_id', $inboundId)
            ->sum('total_amount');
        
        // 更新入库单总金额
        \app\admin\model\scanwork\PurchaseInbound::where('id', $inboundId)
            ->update(['total_amount' => $totalAmount]);
        
        return $totalAmount;
    }

    /**
     * 查看入库明细
     */
    public function viewItems($ids = null)
    {
        if ($this->request->isPost()) {
            // 处理更新明细的请求
            $params = $this->request->post();
            if (isset($params['items']) && is_array($params['items'])) {
                Db::startTrans();
                try {
                    foreach ($params['items'] as $itemId => $itemData) {
                        if (isset($itemData['unit_price']) && isset($itemData['actual_quantity'])) {
                            $unitPrice = floatval($itemData['unit_price']);
                            $actualQuantity = floatval($itemData['actual_quantity']);
                            $totalAmount = $unitPrice * $actualQuantity;
                            
                            \app\admin\model\scanwork\PurchaseInboundItem::where('id', $itemId)
                                ->update([
                                    'unit_price' => $unitPrice,
                                    'actual_quantity' => $actualQuantity,
                                    'total_amount' => $totalAmount
                                ]);
                        }
                    }
                    
                    // 更新入库单总金额
                    $this->updateInboundTotalAmount($ids);
                    
                    Db::commit();
                    $this->success('更新成功');
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error('更新失败：' . $e->getMessage());
                }
            }
        }

        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        // 手动获取关联数据
        $items = \app\admin\model\scanwork\PurchaseInboundItem::where('inbound_id', $ids)->select();
        
        // 手动获取物料信息
        foreach ($items as $item) {
            $item->material = \app\admin\model\scanwork\Material::find($item->material_id);
        }
        
        $supplier = \app\admin\model\scanwork\Supplier::find($row->supplier_id);
        
        $row->items = $items;
        $row->supplier = $supplier;

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
